package com.taijihuabao.modules.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.taijihuabao.common.exception.ServiceException;
import com.taijihuabao.common.jsonresult.ApplicationResponseCode;
import com.taijihuabao.modules.entity.DeptUserEntity;
import com.taijihuabao.modules.entity.RaiseSalaryEntity;
import com.taijihuabao.modules.mapper.DeptUserMapper;
import com.taijihuabao.modules.mapper.RaiseSalaryMapper;
import com.taijihuabao.modules.service.RaiseSalaryService;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 提薪审批流程
 * @author xjt
 */
@Service
public class RaiseSalaryServiceImpl implements RaiseSalaryService {

    @Resource
    RaiseSalaryMapper raiseSalaryMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;
    @Resource
    private DeptUserMapper deptUserMapper;

    /**
     * 主管
     */
    private final String GUANLIYUAN = "administrator";
    /**
     * hr
     */
    private final String SHENHEYUAN = "hr";
    /**
     * 总务部
     */
    private final String ZONGWUBU = "boss";

    @Override
    public void deploy() {
        //部署流程定义并获取流程部署对象
        Deployment deployment = repositoryService
                .createDeployment()
                .name("提薪审批流程")
                .addClasspathResource("bpmn/RaiseSalaryProcess.bpmn")
                .addClasspathResource("bpmn/RaiseSalaryProcess.xml")
                .deploy();
        System.out.println("流程部署Id：" + deployment.getId() + "，" +
                "流程部署name：" + deployment.getName());
    }

    @Override
    public void changeStatus(DelegateExecution execution, String raiseSalaryState) {
        //获取审批单id
        String businessKey = execution.getProcessInstanceBusinessKey();
        //查询审批单
        RaiseSalaryEntity raiseSalaryEntity = raiseSalaryMapper.selectById(Long.valueOf(businessKey));
        //修改状态
        if (Objects.isNull(raiseSalaryEntity)) {
            throw new ServiceException(ApplicationResponseCode.APPROVAL_NOT_FOUND);
        }
        raiseSalaryEntity.setRaiseSalaryState(raiseSalaryState);
        raiseSalaryMapper.updateRaiseSalaryState(raiseSalaryEntity);
        }

    @Override
    public void startProcess(RaiseSalaryEntity raiseSalaryEntity) {
        RaiseSalaryEntity taskApp = raiseSalaryMapper.selectByRaiseCode(raiseSalaryEntity);
        if(!Objects.isNull(taskApp)){
            throw new ServiceException(ApplicationResponseCode.APPROVAL_HAS_EXIST);
        }
        raiseSalaryMapper.insertRaiseSalary(raiseSalaryEntity);
        ProcessInstance instance = runtimeService
                .startProcessInstanceByKey("RaiseSalary", String.valueOf(raiseSalaryEntity.getId()));
        System.out.println(instance);
        //如果申请人可以参与审批单的本部门审批，则自动完成审批
        Long applicant = raiseSalaryEntity.getRaiseUserId();
        List<DeptUserEntity> deptUserEntitys = deptUserMapper.selectDeptByUserId(applicant);
        //判断申请人的身份
        for (DeptUserEntity deptUserEntity : deptUserEntitys){
            String deptRole = deptUserEntity.getDeptRole();
            if(GUANLIYUAN.equals(deptRole)
                    ||SHENHEYUAN.equals(deptRole)){
                //查询该任务并完成
                if(!ZONGWUBU.equals(deptUserEntity.getDeptCode())){
                    aotuComplete(raiseSalaryEntity);
                }
                break;
            }
        }
        //本部门找不到审批人直接去下一节点
        String applyDept = raiseSalaryEntity.getRaiseDeptCode();
        List<DeptUserEntity> applys = deptUserMapper.selectDeptByDeptCode(applyDept);
        if(!CollectionUtils.isEmpty(applys)){
            int result = 0;
            for (DeptUserEntity deptUserEntity2 : applys){
                String deptRole2 = deptUserEntity2.getDeptRole();
                if(GUANLIYUAN.equals(deptRole2)
                        ||SHENHEYUAN.equals(deptRole2)){
                    result = 1;
                    break;
                }
            }
            if(result==0){
                //查询该任务并完成
                aotuComplete(raiseSalaryEntity);
            }
        }
    }
    /**
     * 查询该任务并完成
     * @param raiseSalaryEntity
     */
    public void aotuComplete(RaiseSalaryEntity raiseSalaryEntity){
        List<Task> result = taskService.createTaskQuery()
                .processDefinitionKey("RaiseSalary")
                .processInstanceBusinessKey(String.valueOf(raiseSalaryEntity.getId()))
                .list();
        String task = result.get(0).getId();
        Map<String, Object> map = new HashMap<>(16);
        map.put("agree",1);
        raiseSalaryEntity.setRaiseSalaryUserId(raiseSalaryEntity.getRaiseUserId());
        raiseSalaryEntity.setRaiseSalaryTask(task);
        raiseSalaryEntity.setRaiseSalaryState("ing");
        raiseSalaryMapper.updateRaiseSalary(raiseSalaryEntity);
        taskService.complete(task,map);
    }

    /**
     * 查询待办
     *
     * @param userId
     * @return
     */
    @Override
    public List<RaiseSalaryEntity> findTaskByUserId(String userId) {
        List<Task> result = taskService.createTaskQuery()
                .processDefinitionKey("RaiseSalary")
                .taskCandidateUser(userId).list();
        if(CollectionUtils.isEmpty(result)){
            throw new ServiceException(ApplicationResponseCode.TASK_NOT_FOUND);
        }
        List<RaiseSalaryEntity> taskInfo = new ArrayList<>();
        for(Task task : result){
            String businesskey = task.getBusinessKey();
            RaiseSalaryEntity raiseSalaryEntity = raiseSalaryMapper.selectById(Long.valueOf(businesskey));
            if(!Objects.isNull(raiseSalaryEntity)){
                raiseSalaryEntity.setRaiseSalaryTask(task.getId());
                taskInfo.add(raiseSalaryEntity);
            }
        }
        return taskInfo;
    }

    /**
     * 审核待办
     * @param userId 审核人
     * taskId 审核任务
     * agree  审核结果
     */
    @Override
    public void approvalTask(String userId, RaiseSalaryEntity raiseSalaryEntity) {
        //领取任务
        String taskOne = raiseSalaryEntity.getRaiseSalaryTask();
        taskService.claim(taskOne, userId);
        // 查询当前任务对象
        Task task = ProcessEngines.getDefaultProcessEngine().getTaskService()
                .createTaskQuery().taskId(taskOne).singleResult();
        //获取审批单
        String businessKey = task.getBusinessKey();
        RaiseSalaryEntity approval = raiseSalaryMapper.selectById(Long.valueOf(businessKey));
        Map<String, Object> map = new HashMap<>(16);
        map.put("agree", raiseSalaryEntity.getAgree());

        String perApp = "部门主管";
        if(perApp.equals(task.getName())){
            map.put("agree1", raiseSalaryEntity.getAgree());
            map.remove("agree");
        }

        String topApp = "人力资源部";
        if(topApp.equals(task.getName())){
            map.put("agree2", raiseSalaryEntity.getAgree());
            map.remove("agree");
        }

        String checkApp = "总经办";
        if(checkApp.equals(task.getName())){
            map.put("agree3", raiseSalaryEntity.getAgree());
            map.remove("agree");
        }

        approval.setRaiseSalaryUserId(Long.valueOf(userId));
        approval.setRaiseSalaryRemarks(raiseSalaryEntity.getRaiseSalaryRemarks());
        approval.setRaiseSalaryTask(taskOne);
        raiseSalaryMapper.updateRaiseSalary(approval);
        taskService.complete(taskOne,map);
    }
}
